package com.study.module.ratelimit;

import org.redisson.api.RRateLimiter;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Optional;

/**
 * @author: 王霄
 * @date: 2021/9/6 21:31
 */
@Service
public class RateLimitService {

    private final static String RATE_PREFIX = "RATE_LIMIT:";

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public RRateLimiter getRateLimiter(String name) {
        return redissonClient.getRateLimiter(RATE_PREFIX.concat(name));
    }

    @PostConstruct
    public void clearAllRateLimiterKey() {
        Optional.ofNullable(redisTemplate.keys(RATE_PREFIX.concat("*")))
                .orElse(new HashSet<>())
                .forEach(key -> redissonClient.getRateLimiter(key).delete());
    }
}
